﻿using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ymca.DataAccess;
using Ymca.Entities;
using Ymca.Infrastrucure;
using Ymca.Web.Services.Interfaces;

namespace Ymca.Web.Services
{
	public class SearchService: ISearchService
	{
		public IEnumerable<Post> Search(string search)
		{
			return Search(1, Constants.PgeSize, search);
		}

		public IPagedList<Post> Search(int page, int pageSize, string search)
		{
			if (string.IsNullOrEmpty(search))
			{
				return Enumerable.Empty<Post>().ToPagedList<Post>(page, pageSize);
			}
			using (DataContext dc = new DataContext())
			{
				//We need to order results before using a paging. The expection will be thrown if to skip this step.
				IPagedList<Post> posts = dc.Posts.OrderBy(p => p.Id).Where(post => post.Title.Contains(search)
					|| post.Body.Contains(search)).ToPagedList<Post>(page, pageSize);

				foreach (Post post in posts)
				{
					//post.Attachments = dc.Attachments.Where(a => a.PostId.Equals(post.Id)).ToList();
					//post.Comments = dc.Comments.Where(c => c.PostId.Equals(post.Id)).ToList();
				}
				return posts;
			}
		}
	}
}